package com.yu.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.shortlink.admin.common.biz.user.UserContext;
import com.yu.shortlink.admin.common.convention.result.Result;
import com.yu.shortlink.admin.dao.entity.GroupDO;
import com.yu.shortlink.admin.dao.mapper.GroupMapper;
import com.yu.shortlink.admin.dto.req.ShortLinkGroupSortReqDTO;
import com.yu.shortlink.admin.dto.req.ShortLinkGroupUpdateReqDTO;
import com.yu.shortlink.admin.dto.resp.ShortLinkGroupResDTO;
import com.yu.shortlink.admin.remote.dto.ShortLinkRemoteService;
import com.yu.shortlink.admin.remote.dto.resp.ShortLinkGroupCountQueryRespDTO;
import com.yu.shortlink.admin.service.GroupService;
import com.yu.shortlink.admin.toolkit.RandomGenerator;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
* @author 哈哈哈呜呜呜
* @description 针对表【t_group】的数据库操作Service实现
* @createDate 2024-04-06 15:51:52
*/
@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO>
    implements GroupService {

    /**
     * 后续重构SpringCloud Feign调用
     */
    ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService() {
    };


    @Override
    public void saveGroup(String groupName) {
        this.saveGroup(UserContext.getUsername(),groupName);
    }

    @Override
    public void saveGroup(String username, String groupName) {
        String gid;
        do {
            gid = RandomGenerator.generateRandom();
        } while (!hasGid(username,gid));
        GroupDO groupDO = GroupDO.builder()
                .name(groupName)
                .gid(gid)
                .username(username)
                .sortOrder(0)
                .build();
        baseMapper.insert(groupDO);
    }

    @Override
    public List<ShortLinkGroupResDTO> listGroup() {
        // 获取用户名
        LambdaQueryWrapper<GroupDO> wrapper = new LambdaQueryWrapper<GroupDO>()
                .eq(GroupDO::getDelFlag,0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .orderByDesc(List.of(GroupDO::getSortOrder,GroupDO::getUpdateTime));
        List<GroupDO> groupDOList = baseMapper.selectList(wrapper);
        List<ShortLinkGroupResDTO> shortLinkGroupResDTOS = BeanUtil.copyToList(groupDOList, ShortLinkGroupResDTO.class);

        // 查询短链接数量(gid)
        Result<List<ShortLinkGroupCountQueryRespDTO>> listResult = shortLinkRemoteService.listGroupShortLinkCount(shortLinkGroupResDTOS.stream().map(ShortLinkGroupResDTO::getGid).collect(Collectors.toList()));
        List<ShortLinkGroupCountQueryRespDTO> data = listResult.getData();

        shortLinkGroupResDTOS.forEach(item->{
            ShortLinkGroupCountQueryRespDTO shortLinkGroupCountQueryRespDTO = data.stream().filter(record -> Objects.equals(item.getGid(), record.getGid())).findFirst().orElse(null);
            item.setShortLinkCount(shortLinkGroupCountQueryRespDTO.getShortLinkCount());

        });
        return shortLinkGroupResDTOS;
    }

    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDTO requestParam) {
        LambdaQueryWrapper<GroupDO> eq = new LambdaQueryWrapper<GroupDO>()
                .eq(GroupDO::getGid, requestParam.getGid())
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag,0);
        GroupDO groupDO = new GroupDO();
        groupDO.setName(requestParam.getName());
        baseMapper.update(groupDO,eq);

    }

    @Override
    public void deleteGroup(String gid) {
        LambdaQueryWrapper<GroupDO> eq = new LambdaQueryWrapper<GroupDO>()
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag,0);
        GroupDO groupDO = new GroupDO();
        groupDO.setDelFlag(1);
        baseMapper.update(groupDO,eq);
    }

    @Override
    public void sortGroup(List<ShortLinkGroupSortReqDTO> requestParam) {
        requestParam.forEach(each->{
            GroupDO groupDO = GroupDO.builder()
                    .sortOrder(each.getSortOrder())
                    .build();
            LambdaQueryWrapper<GroupDO> eq = new LambdaQueryWrapper<GroupDO>()
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getGid, each.getGid())
                    .eq(GroupDO::getDelFlag, 0);
            baseMapper.update(groupDO,eq);
        });
    }


    private Boolean hasGid(String username,String gid) {
        LambdaQueryWrapper<GroupDO> eq = new LambdaQueryWrapper<GroupDO>()
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, Optional.ofNullable(username).orElse(UserContext.getUsername()));
        GroupDO groupDO = baseMapper.selectOne(eq);
        return Objects.isNull(groupDO);
    }
}




